package com.gpay.erp.web.control;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.gpay.erp.services.common.GlobalStatus;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.support.RequestContext;
import com.gpay.erp.core.dao.page.PageHelper;
import com.gpay.erp.core.dao.page.PagerModel;
import com.gpay.erp.core.system.bean.SysUser;
import com.gpay.erp.services.system.SysUserInteface;
import com.gpay.erp.web.util.WebUtil;
import com.gpay.erp.web.vo.ResponseInfo;

/**
 * 用户/员工管理
 * 
 * @author lg
 * 
 */
@Controller
@RequestMapping("/sysUserController/")
public class SysUserController extends BaseController {
	private Log log = LogFactory.getLog(SysUserController.class);
	@Autowired
	private SysUserInteface sysUserService;
	@Autowired
	private GlobalStatus globalStatus;

	// 页面跳转 用户管理
	@RequestMapping("userMenu")
	public String userMenu() {
		return "system/sysUser/userMenu";
	}

	// 页面跳转 用户新增
	@RequestMapping("userAdd")
	public String userAdd() {
		return "system/sysUser/userAdd";
	}

	// 页面跳转 用户修改
	@RequestMapping("userUpdate")
	public String userUpdate(String id, ModelMap modelMap) {
		modelMap.addAttribute("userId", id);
		return "system/sysUser/userUpdate";
	}

	// 页面跳转 角色授权
	@RequestMapping("userGrant")
	public String userGrant(String id, ModelMap modelMap) {
		modelMap.addAttribute("userId", id);
		return "system/sysUser/userGrant";
	}

	// 页面跳转 分配负责部门
	@RequestMapping("distributeDept")
	public String distributeDept(String id, ModelMap modelMap) {
		modelMap.addAttribute("userId", id);
		return "system/sysUser/distributeDept";
	}

	// 用户状态
	@RequestMapping("userGlobalStatus")
	public void userGlobalStatus(HttpServletRequest request,
			HttpServletResponse response) {
		ResponseInfo responseInfo = new ResponseInfo();
		/* 获取用户状态，传递给页面 */
		responseInfo.setResult("00010");
		responseInfo.setMessage("select.success");
		responseInfo.setObject(globalStatus.getUserStatus());
		WebUtil.responseToJson(response, responseInfo);
	}

	// 用户性别
	@RequestMapping("userSexGlobalStatus")
	public void userSexGlobalStatus(HttpServletRequest request,
			HttpServletResponse response) {
		ResponseInfo responseInfo = new ResponseInfo();
		/* 获取用户性别状态，传递给页面 */
		responseInfo.setResult("00010");
		responseInfo.setMessage("select.success");
		responseInfo.setObject(globalStatus.getSexMap());
		WebUtil.responseToJson(response, responseInfo);
	}

	/*
	 * 用户管理，进行分页查询
	 * 
	 * @param pageHelper
	 * 
	 * @param request
	 * 
	 * @param response
	 */
	@RequestMapping("selectUser")
	public void selectUser(PagerModel pagerModel, SysUser sysUser,
			PageHelper pageHelper, HttpServletRequest request,
			HttpServletResponse response) {
		RequestContext requestContext = new RequestContext(request);
		ResponseInfo responseInfo = new ResponseInfo();
		/* 当前页 */
		int pagenow = pageHelper.getPage();
		/* 每页显示记录数 */
		int rows = pageHelper.getRows();
		/* 分页信息填充进入PagerModel中 */
		sysUser.setPageSize(rows);
		sysUser.setFromRow((pagenow - 1) * rows);
		sysUser.setToRow(pagenow * rows);
		/* 查询数据，返回PagerModel */
		pagerModel = sysUserService.selectPageList(sysUser);
		if (pagerModel.getRows().size() > 0) {
			for (Object hashMap : pagerModel.getRows()) {
				SysUser hashMap1 = (SysUser) hashMap;
				int key = Integer.parseInt(hashMap1.getSex().toString());
				switch (key) {
				case 0:
					hashMap1.setSex(globalStatus.getSexMap().get("0")
							.toString());
					break;
				case 1:
					hashMap1.setSex(globalStatus.getSexMap().get("1")
							.toString());
					break;
				}
				int statuskey = Integer.parseInt(hashMap1.getStatus()
						.toString());
				switch (statuskey) {
				case 0:
					hashMap1.setStatus(globalStatus.getUserStatus().get("0")
							.toString());
					break;
				case 1:
					hashMap1.setStatus(globalStatus.getUserStatus().get("1")
							.toString());
					break;
				}
			}
			responseInfo.setResult("10030");
			responseInfo.setMessage(requestContext
					.getMessage("user.res.success"));
		}
		responseInfo.setObject(pagerModel);
		WebUtil.responseToJson(response, responseInfo);

	}

	/*
	 * 查询所有用户信息 返回单表list
	 * 
	 * @param request
	 * 
	 * @param response
	 */
	@RequestMapping("selectListAll")
	public void selectListAll(SysUser sysUser, HttpServletRequest request,
			HttpServletResponse response) {
		RequestContext requestContext = new RequestContext(request);
		ResponseInfo responseInfo = new ResponseInfo();
		List<SysUser> userList = sysUserService.selectList(sysUser);
		if (userList.size() > 0) {
			responseInfo.setResult("11000");
			responseInfo.setMessage(requestContext
					.getMessage("user.res.success"));
		}
		responseInfo.setObject(userList);
		WebUtil.responseToJson(response, responseInfo);
	}

	/*
	 * 点击新增，增加新用户
	 * 
	 * @param sysUser
	 * 
	 * @param request
	 * 
	 * @param response
	 */
	@RequestMapping("addUser")
	public void addUser(SysUser sysUser, HttpServletRequest request,
			HttpServletResponse response) {
		RequestContext requestContext = new RequestContext(request);
		ResponseInfo responseInfo = new ResponseInfo();
		HttpSession session = request.getSession();
		/* 获取登录的用户信息 */
		SysUser loginUser = (SysUser) session.getAttribute("loginUser");
		if (request.getParameterValues("roleIdsArray[]") != null) {
			sysUser.setRoleIds(request.getParameterValues("roleIdsArray[]"));
		} else {
			sysUser.setRoleIds(request.getParameterValues("roleIdsArray"));
		}
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
		sysUser.setCreatedate(df.format(new Date()));
		sysUser.setCreateName(loginUser.getUserName());
		sysUser.setF_account(loginUser.getF_account());
		sysUser.setAccountName(loginUser.getAccountName());
		if (sysUser.getId() == null) {
			int id = sysUserService.insert(sysUser);// 执行新增用户操作，返回t_user表新增行的id
			log.info("t_user表插入记录的id值为：" + id);
			responseInfo.setResult("00040");
			responseInfo.setMessage(requestContext.getMessage("add.success"));
			if (id != 0 && sysUser.getRoleIds() != null) {
				sysUser.setUserId(id + "");
				int tId = sysUserService.insertRoleUser(sysUser);// 赋予用户角色
				if (tId != 0) {
					responseInfo.setResult("00040");
					responseInfo.setMessage(requestContext
							.getMessage("add.success"));
				} else {
					responseInfo.setResult("00041");
					responseInfo.setMessage(requestContext
							.getMessage("add.fail"));
				}
			}
		}
		WebUtil.responseToJson(response, responseInfo);
	}

	/*
	 * 点击明细，查看用户详细信息
	 * 
	 * @param sysUser
	 * 
	 * @param request
	 * 
	 * @param response
	 */
	@RequestMapping("detailUser")
	public void detailUser(PagerModel pagerModel, SysUser sysUser,
			HttpServletRequest request, HttpServletResponse response) {
		RequestContext requestContext = new RequestContext(request);
		ResponseInfo responseInfo = new ResponseInfo();
		if (sysUser.getId() != null) {
			/* 根据ID查询用户明细 */
			pagerModel = sysUserService.selectOne(sysUser);
			if (pagerModel != null) {
				responseInfo.setResult("00010");
				responseInfo.setMessage(requestContext
						.getMessage("select.success"));
			} else {
				responseInfo.setResult("00011");
				responseInfo.setMessage(requestContext
						.getMessage("select.fail"));
			}
		} else {
			responseInfo.setResult("00011");
			responseInfo.setMessage(requestContext.getMessage("select.fail"));
		}
		responseInfo.setObject(pagerModel);
		WebUtil.responseToJson(response, responseInfo);
	}

	/*
	 * 点击修改，修改用户信息
	 * 
	 * @param sysUser
	 * 
	 * @param request
	 * 
	 * @param response
	 */
	@RequestMapping("updateUser")
	public void updateUser(SysUser sysUser, HttpServletRequest request,
			HttpServletResponse response) {
		RequestContext requestContext = new RequestContext(request);
		ResponseInfo responseInfo = new ResponseInfo();
		HttpSession session = request.getSession();
		/* 获取登录的用户信息 */
		SysUser loginUser = (SysUser) session.getAttribute("loginUser");
		/* 设置日期格式 */
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		/* 获取当地时间 */
		if (request.getParameterValues("roleIdsArray[]") != null) {
			sysUser.setRoleIds(request.getParameterValues("roleIdsArray[]"));
		} else if (request.getParameter("roleIdsArray") != null) {
			sysUser.setRoleIds(request.getParameter("roleIdsArray").split(","));
		}
		sysUser.setCreatedate(df.format(new Date()));
		sysUser.setCreateName(loginUser.getUserName());
		if (sysUser.getId() != null) {
			/* 执行用户信息修改操作，返回t_user表修改行的id */
			int id = sysUserService.update(sysUser);
			if(id!=0){	
				responseInfo.setResult("00030");
			    responseInfo.setMessage(requestContext.getMessage("update.success"));			   
			if (sysUser.getRoleIds() != null) {
				sysUser.setUserId(id + "");
				int flag = sysUserService.insertRoleUser(sysUser);
				if (flag != 0) {
					responseInfo.setResult("00030");
					responseInfo.setMessage(requestContext
							.getMessage("update.success"));
				} else {
					responseInfo.setResult("00031");
					responseInfo.setMessage(requestContext
							.getMessage("update.fail"));
				}
			} }else
		    {
		    	responseInfo.setResult("00031");
				responseInfo.setMessage(requestContext
						.getMessage("update.fail"));
		    }
		} else {
			responseInfo.setResult("00031");
			responseInfo.setMessage(requestContext.getMessage("update.fail"));
		}
		WebUtil.responseToJson(response, responseInfo);
	}
	/*
	 * 点击禁用，根据id禁用用户 
	 * 
	 * @param ids[]
	 * 
	 * @param request
	 * 
	 * @param response
	 */
	@RequestMapping("disableSysUser")
	public void disableSysUser(HttpServletRequest request,
			HttpServletResponse response) {
		RequestContext requestContext = new RequestContext(request);
		ResponseInfo responseInfo = new ResponseInfo();
		HttpSession session = request.getSession();
		/* 获取登录的用户信息 */
		SysUser loginUser = (SysUser) session.getAttribute("loginUser");
		String name=loginUser.getUserName();
		String[] ids = null;
		if (request.getParameterValues("ids[]") != null) {
			ids = request.getParameterValues("ids[]");// 接收前端传输的id值
		} else {
			ids = request.getParameterValues("ids");// 接收前端传输的id值
		}
		if (ids != null) {
			int dels = sysUserService.update(ids,name);// 根据传入id修改用户Status
			if (dels != 0) {
				responseInfo.setResult("00050");
				responseInfo.setMessage(requestContext
						.getMessage("disable.success"));
			} else {
				responseInfo.setResult("00051");
				responseInfo.setMessage(requestContext
						.getMessage("disable.fail"));
			}
		} else {
			responseInfo.setResult("00051");
			responseInfo.setMessage(requestContext.getMessage("disable.fail"));
		}
		WebUtil.responseToJson(response, responseInfo);
	}
	
	/*
	 * 点击删除，根据id删除用户信息
	 * 
	 * @param ids[]
	 * 
	 * @param request
	 * 
	 * @param response
	 */
	@RequestMapping("deleteUser")
	public void deleteUser(HttpServletRequest request,
			HttpServletResponse response) {
		RequestContext requestContext = new RequestContext(request);
		ResponseInfo responseInfo = new ResponseInfo();
		HttpSession session = request.getSession();
		/* 接收前端传输的id值 */
		String[] ids = request.getParameterValues("ids[]");
		if (ids != null) {
			/* 执行删除操作，删除成功返回1，失败返回0 */
			int dels = sysUserService.deletes(ids);
			if (dels != 0) {
				responseInfo.setResult("00020");
				responseInfo.setMessage(requestContext
						.getMessage("delete.success"));
			} else {
				responseInfo.setResult("00021");
				responseInfo.setMessage(requestContext
						.getMessage("delete.fail"));
			}
		} else {
			responseInfo.setResult("00021");
			responseInfo.setMessage(requestContext.getMessage("delete.fail"));
		}
		WebUtil.responseToJson(response, responseInfo);
	}

	/*
	 * 根据用户ID查询该用户所属角色ID,用于前端对比
	 * 
	 * @param sysUser
	 * 
	 * @param request
	 * 
	 * @param response
	 */
	@RequestMapping("selectUserRoles")
	public void selectUserRoles(SysUser sysUser, HttpServletRequest request,
			HttpServletResponse response) {
		RequestContext requestContext = new RequestContext(request);
		ResponseInfo responseInfo = new ResponseInfo();
		List<SysUser> rolesList = new ArrayList<SysUser>();
		List roleIds = new ArrayList();
		/* 获取前端传入的id,判断是否为null */
		if (sysUser.getId() != null) {
			/* 根据用户ID查询该用户所属角色ID */
			rolesList = sysUserService.findRoles(sysUser);
			for (int i = 0; i < rolesList.size(); i++) {
				roleIds.add(rolesList.get(i).getRoleId());
			}
			responseInfo.setResult("00010");
			responseInfo
					.setMessage(requestContext.getMessage("select.success"));
		} else {
			responseInfo.setResult("00011");
			responseInfo.setMessage(requestContext.getMessage("select.fail"));
		}
		responseInfo.setObject(roleIds);
		WebUtil.responseToJson(response, responseInfo);
	}
	/*
	 * 根据员工工号userNo或者员工账户userName查询是否有重复
	 * 
	 * @param sysUser
	 * 
	 * @param request
	 * 
	 * @param response
	 */
	@RequestMapping("selectUserNoAndUserName")
	public void selectUserNoAndUserName(PagerModel pagerModel,SysUser sysUser, HttpServletRequest request,
			HttpServletResponse response) {
		RequestContext requestContext = new RequestContext(request);
		ResponseInfo responseInfo = new ResponseInfo();
		/* 获取前端传入的userNo,判断是否为null */
		if (sysUser.getUserNo()!= null||sysUser.getUserName()!=null) {
			pagerModel = sysUserService.selectOne(sysUser);
			if(pagerModel!=null){
			responseInfo.setResult("10040");
			responseInfo.setMessage(requestContext.getMessage("data.repeat"));
			}else
			{
				responseInfo.setResult("10050");
				responseInfo.setMessage(requestContext.getMessage("data.norepeat"));
			}
		}else{
			responseInfo.setResult("10041");
			responseInfo.setMessage(requestContext.getMessage("data.receive.fail"));
		}
		WebUtil.responseToJson(response, responseInfo);
	}
}
